package org.alex.samples.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.alex.samples.dao.IExamScoreDAO;
import org.alex.samples.dao.IExamSubjectDAO;
import org.alex.samples.dao.IExamTestDAO;
import org.alex.samples.dao.IExamTestTypeDAO;
import org.alex.samples.dao.IUserJdbcDAO;
import org.alex.samples.model.ExamScore;
import org.alex.samples.model.ExamScoreVO;
import org.alex.samples.model.ExamSubject;
import org.alex.samples.model.ExamSubjectVO;
import org.alex.samples.model.ExamTest;
import org.alex.samples.model.ExamTestType;
import org.alex.samples.model.ExamTestTypeVO;
import org.alex.samples.model.ExamTestVO;
import org.alex.samples.model.ExamUserVO;
import org.alex.samples.model.UserJDBC;
import org.alex.samples.util.TestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class StudentServiceImpl implements IStudentService {
	@Autowired
	private IUserJdbcDAO examUserDAO;
	
	@Autowired
	private IExamScoreDAO examScoreDAO;
	
	@Autowired
	private IExamTestTypeDAO examTestTypeDAO;
	
	@Autowired
	private IExamTestDAO examTestDAO;
	
	@Autowired
	private IExamSubjectDAO examSubjectDAO;
	

	//通过科目得到试题的方法
	@Override
	public Map<Integer, List<ExamTestVO>> getTestListBySubject(Integer subId, String userId) {
		// 初始化参数
		List<ExamTestType> examTestType = examTestTypeDAO.loadAll();
		Map<Integer, Integer> testTypeScoreMap = new HashMap<Integer, Integer>();
		// 所有题型各自的分数
		Map<Integer,  List<ExamTestVO>>  testListMap  =  new  HashMap<Integer, List<ExamTestVO>>();
		// 获取所有题型，得到testTypeScoreMap
		if (examTestType != null) {
			for (ExamTestType testType : examTestType) {
				testTypeScoreMap.put(testType.getId(), testType.getTestTypeScore());
				//System.out.println("TestTypeId"+testType.getId());
				
				// 3.0. 根据科目获取各个题型所有题目
				List<ExamTest> testList = examTestDAO.getTestListBySubAndTestType(subId, testType.getId());
				//System.out.println("testList" + testList.size());
				List<ExamTestVO> testVOList = new ArrayList<ExamTestVO>();
				// 分别获取各个题型在数据库里的所有题目
				for (ExamTest test : testList) {
					ExamTestVO vo = new ExamTestVO();
					BeanUtils.copyProperties(test, vo);
					ExamTestTypeVO testTypeVO = new ExamTestTypeVO();
					BeanUtils.copyProperties(test.getExamTestType(), testTypeVO);
					vo.setExamTestType(testTypeVO);
					testVOList.add(vo);
					}
				testListMap.put(testType.getId(), testVOList);//
				}
		} else {
			return null;
			}
		
		ExamSubject subject = examSubjectDAO.get(subId);
		if (subject == null) {
			return null;
			}
		Integer totalTestScore = subject.getTotalScore().intValue();
		Integer totalTestCount = subject.getTestCount();
		
		/*System.out.println("subject" + subject.getTestCount());
		System.out.println();
		System.out.println("测试--------------");
		System.out.println("totalTestCount" + totalTestCount);
		System.out.println("totalTestScore" + subject.getTotalScore().intValue());
		System.out.println("testTypeScoreMap" + testTypeScoreMap);
		System.out.println("examTestType" + examTestType.size() );*/
		
		// 1. 校验科目总分和总题数是否匹配
		if ( !TestUtils.checkSubjectScoreAndCount(totalTestCount, totalTestScore, testTypeScoreMap)) {
			return null;
			}
		
		//System.out.println("sfahsjkdfhaskjdfhsadkjfhasdkfashfjkashkf");
		
		// 2. 获取各个题型的数量
		Map<Integer, Integer>  testTypeCountMap  = TestUtils.getTestCountByScore(totalTestCount , totalTestScore, testTypeScoreMap,  examTestType);
		
		//System.out.println("testTypeCountMap"+testTypeCountMap);
		
		// 4. 生成随机题目
		Map<Integer,  List<ExamTestVO>>  resultTestListMap  =  new  HashMap<Integer, List<ExamTestVO>>();
		for (Integer key : testTypeCountMap.keySet()) {
			Integer count = testTypeCountMap.get(key);
			
			//System.out.println("testTypeCountMap.keySet()"+testTypeCountMap.keySet());
			//System.out.println("count"+count);
			
			List<ExamTestVO> testList = testListMap.get(key);
			// 3.1 在里面
			List<Integer> randomTestIdList = TestUtils.getRandomTestIdList(testList, count);
			if (randomTestIdList == null) {
				return null;
				}
			
			//System.out.println("randomTestIdList"+randomTestIdList);
			
			
			// 根据多个id获取多个题目
			List<ExamTest> randomTestList = examTestDAO.getTestListByIdList(randomTestIdList);
			// 转换List<ExamTest> ==>List<ExamTestVO>
			
			//System.out.println("randomTestList:"+randomTestList.size());
			
			List<ExamTestVO> testVOList = new ArrayList<ExamTestVO>();
			for (ExamTest test : randomTestList) {
				ExamTestVO vo = new ExamTestVO();
				BeanUtils.copyProperties(test, vo);
				ExamTestTypeVO testTypeVO = new ExamTestTypeVO();
				BeanUtils.copyProperties(test.getExamTestType(), testTypeVO);
				vo.setExamTestType(testTypeVO);
				testVOList.add(vo);
				}
			
			//System.out.println("testVOList"+testVOList);
			
			  resultTestListMap.put(key, testVOList);//
			}
		
		ExamScore score = new ExamScore();
		score.setUserId(userId);
		score.setSubjectId(subId);
		score.setExamTime(new Date());
		// 如果成功取到试题
		
		examScoreDAO.save(score);
		examScoreDAO.flush();
		
		return resultTestListMap;
		
	}	
			
		
	//计算得分
	@Override
	public void calculateScore(List<Integer> answerIds, Map<String, String[]> testMap, String userId,
			Integer subId) {
		Integer score = 0;
		List<ExamTest> randomTestList = examTestDAO.getTestListByIdList(answerIds);
		for(ExamTest test : randomTestList){
			boolean flag = false;
			String type = test.getExamTestType().getTestType();
			String[] answer = testMap.get(String.valueOf(test.getId()));
			if("单选题".equals(type)){
				if(test.getAnswer().equals(answer[0])){
					flag = true;
				}
			}else if("双选题".equals(type)){
				String[] testAnswer = test.getAnswer().split(",");
				if(answer.length == testAnswer.length){
					for(int i = 0; i < answer.length; i++){
						if(testAnswer[i].equals(answer[i])){
							flag = true;
						}else{
							flag = false;
							break;
						}
					}
				}else{
					flag = false;
				}
			}
			if(flag){
				score = score + test.getExamTestType().getTestTypeScore();
			}
		}
		examScoreDAO.editScore(userId, subId, score);
	}
		
	
	//获取某学生的参考科目
	@Override
	public List<ExamSubjectVO> getSubjectList(ExamUserVO userVO) {
		List<ExamSubjectVO> resultList=new ArrayList<ExamSubjectVO>();
		//读取所有科目
		UserJDBC user=examUserDAO.get(userVO.getUserId());
		Collection<ExamSubject> subs=user.getExamSubject();
		for(ExamSubject sub:subs){
			ExamSubjectVO subVO=new ExamSubjectVO();
			BeanUtils.copyProperties(sub, subVO);
			//读取对应科目的成绩
			ExamScore score=examScoreDAO.getScore(userVO.getUserId(),subVO.getSubId());
			if(score!=null){
				ExamScoreVO scoreVO=new ExamScoreVO();
				BeanUtils.copyProperties(score, scoreVO); 
				
				//计算剩余考试成绩
				Calendar startTime=Calendar.getInstance();
				startTime.setTime(scoreVO.getExamTime());
				Calendar currentTime=Calendar.getInstance();
				currentTime.setTime(new Date());
				long startSecond=startTime.getTimeInMillis();
				long currentSecond=currentTime.getTimeInMillis();
				long totalSecond=sub.getTotalTime()*60;
				scoreVO.setRemainingExamTime(totalSecond - (currentSecond-startSecond)/1000);
				subVO.setScore(scoreVO);
			}
			resultList.add(subVO);
		}
		return resultList;
	}

	//得到科目的分数
	@Override
	public ExamScoreVO getScoreById(Integer scoreId) {
		ExamScoreVO vo=examScoreDAO.getScoreById(scoreId);
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm");
		vo.setExamTimeString(df.format(vo.getExamTime()));
		return vo;
	}






	
	
}









